#!/bin/bash
#set -x
WORK_PATH=$(readlink -f ${0} | xargs dirname)
script_name=$(basename $0)
source ${WORK_PATH}/${script_name%\.*}.conf
log="${WORK_PATH}/log/${script_name%\.*}.log"
DATE=$(date +%Y%m%d)
start_time_s=$(date +%s)
result_check_log="${WORK_PATH}/log/${script_name%\.*}_$(date +%Y%m%d%H%M%S).log"
result_branch_info="${WORK_PATH}/log/${script_name%\.*}_branch_info_$(date +%Y%m%d%H%M%S).txt"
USER_ID=`id -u`
######################################################
# common function
######################################################
function start_run
{
    if [[ -e ${WORK_PATH}/log ]]; then
        rm -rf ${WORK_PATH}/log/*
    else
        mkdir -p ${WORK_PATH}/log
    fi

    :> ${log}

    if [[ -e ${LOG_PATH}/yocto-build-${DATE} ]]; then
        echo "[INFO ] ${LOG_PATH}/yocto-build-${DATE} exists." | tee -a ${log}
    else
        mkdir -p ${LOG_PATH}/yocto-build-${DATE}
        mkdir -p ${LOG_PATH}/yocto-build-${DATE}-bak
        echo "[INFO ] mkdir ${LOG_PATH}/yocto-build-${DATE} Success." | tee -a ${log}
    fi
    echo "#####################################################"  | tee -a ${log}
    echo "# Start Time     : $(date +%Y/%m/%d-%H:%M:%S)"          | tee -a ${log}
    echo "#####################################################"  | tee -a ${log}
    echo ""
}

function succ_exit
{
    local end_time_s=$(date +%s)
    echo "######################################################"  | tee -a ${log}
    echo "# Execution Result : Success "                           | tee -a ${log}
    echo "# Execution Time   : $[ $end_time_s - $start_time_s ]s"  | tee -a ${log}
    echo "# End Time         : $(date +%Y%m%d-%H:%M:%S)"           | tee -a ${log}
    echo "######################################################"  | tee -a ${log}
    exit 0
}

function abnormal_exit
{
    local end_time_s=$(date +%s)
    echo "######################################################"  | tee -a ${log}
    echo "# Execution Result : ERROR !!! "                         | tee -a ${log}
    echo "# Execution Time   : $[ $end_time_s - $start_time_s ]s"  | tee -a ${log}
    echo "# End Time         : $(date +%Y%m%d-%H:%M:%S)"           | tee -a ${log}   
    echo "######################################################"  | tee -a ${log}
    exit 1
}

function docker_restart
{
    echo ">>>>>>>>>>> docker_restart start >>>>>>>>>>>>" | tee -a ${log}
    echo "[INFO] Restart docker container."
    if [[ ${XDG_RUNTIME_DIR} == "" ]];then
		echo "[INFO ] export XDG_RUNTIME_DIR= ["
		export XDG_RUNTIME_DIR=/run/user/${USER_ID}
		echo ${XDG_RUNTIME_DIR}
		echo "]"
	fi

    export DISPLAY=:0.0
    (${DOCKER_SCRIPT_COMMAND} restart 2>&1)
    if [[ $? -ne 0 ]]; then
        echo "[ERR ] Failed to restart docker container." | tee -a ${log}
        abnormal_exit
    fi
    echo "[INFO] Successfully restart docker container." | tee -a ${log}
    sleep 30
    echo "<<<<<<<<<<< docker_restart end <<<<<<<<<<<<<" | tee -a ${log}
    echo ""
}

function runtime_docker_backup
{
    echo ">>>>>>>>>>>>>>>>>>>>>>>>>> runtime_docker_backup start>>>>>>>>>>>>>>>>>>>>>>>>>>>" | tee -a ${log}
    cd ${RUNTIME_DOCKER_PATH}
    ll
    local runtime_docker_filename=$(ls arene-image-cockpit-ivi-genericx86-64-*.rootfs.tar.bz2)
    echo "[INFO ] === the new runtime_docker_filename = [${runtime_docker_filename}]" | tee -a ${log}

    cp ${runtime_docker_filename} ${LOG_PATH}/yocto-build-${DATE}/
    if [[ $? -ne 0 ]]; then     
        echo "[ERR ] ${RUNTIME_DOCKER_PATH}/${RUNTIME_DOCKER} is not found !!!" | tee -a ${log}
        abnormal_exit
    else
        echo "[INFO ] [${RUNTIME_DOCKER_PATH}/${runtime_docker_filename}] back to [${LOG_PATH}/yocto-build-${DATE}] success" | tee -a ${log}
    fi
    echo "<<<<<<<<<<<<<<<<<<<<<<<< runtime_docker_backup end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" | tee -a ${log}
    echo ""
}

function docker_install
{
    echo ">>>>>>>>>>>>>>>>>>>>>>>>>> docker_install start>>>>>>>>>>>>>>>>>>>>>>>>>>>" | tee -a ${log}
    cd ${DOCKER_PATH}

    local docker_registry=$(grep DOCKER_REGISTRY ./.env | cut -d = -f 2)
    local docker_image_runtime_name=$(grep DOCKER_IMAGE_RUNTIME_NAME ./.env | cut -d = -f 2)
    local docker_image_runtime_tag=$(grep DOCKER_IMAGE_RUNTIME_TAG ./.env | cut -d = -f 2)
    local docker_name="sdk-docker-runtime_${docker_image_runtime_tag}.tar.gz"

    docker stop ${RUNTIME_DOCKER_NAME}
    if [[ $? -ne 0 ]]; then     
        echo "[ERR ] Failed to docker stop sdk-hal-docker_arene_1 !!!" | tee -a ${log}
        abnormal_exit
    fi
    echo "[INFO ] docker stop sdk-hal-docker_arene_1 Success" | tee -a ${log}

    docker rm -f ${RUNTIME_DOCKER_NAME}
    if [[ $? -ne 0 ]]; then     
        echo "[ERR ] Failed to docker rm -f sdk-hal-docker_arene_1 !!!" | tee -a ${log}
        abnormal_exit
    fi
    echo "[INFO ] docker rm -f sdk-hal-docker_arene_1 Success" | tee -a ${log}

    local runtime_image_id=$(docker images ${docker_registry}/${docker_image_runtime_name}:${docker_image_runtime_tag} --format "{{.ID}}")
    if [[ ${runtime_image_id} != "" ]]; then
        docker rmi -f  ${runtime_image_id}
        if [[ $?  -ne 0 ]]; then
            echo "[ERR ] Failed to docker rmi -f image.ID=>${runtime_image_id} !!!" | tee -a ${log}
            abnormal_exit
        fi
    fi
    echo "[INFO ] docker rmi -f image.ID=>${runtime_image_id} Success" | tee -a ${log}

    docker import ${docker_name} ${docker_registry}/${docker_image_runtime_name}:${docker_image_runtime_tag}
    if [[ $?  -ne 0 ]]; then
        echo "[ERR ] Failed to docker import ${docker_name} ${docker_registry}/${docker_image_runtime_name}:${docker_image_runtime_tag} !!!" | tee -a ${log}
        abnormal_exit
    fi
    echo "[INFO ] docker import ${docker_name} ${docker_registry}/${docker_image_runtime_name}:${docker_image_runtime_tag} Success" | tee -a ${log}

    docker_restart
    
    echo "[INFO ] docker restart Success" | tee -a ${log}
    echo "<<<<<<<<<<<<<<<<<<<<<<<<<< docker_install end<<<<<<<<<<<<<<<<<<<<<<<<<<<" | tee -a ${log}
    echo ""
}

function result_check
{
    echo "---------------check repo info in the yocto (start)--------------" | tee -a ${result_branch_info}

    for repo_recipes in ${YOCTO_CHECK_REPO_RECIPES[@]}; do 
        tmp_array=(${repo_recipes//:/ })
        repo=${tmp_array[0]}
        recipes=${tmp_array[1]}
        if [[ $(ls ${CODE_PATH}/${recipes} |wc -l) -eq 1 ]];then
            pushd ${CODE_PATH}/${recipes}/*/git
            {
                echo "-------------- repo = ${repo_recipes}---------------" | tee -a  ${result_branch_info}
                SRC_URI="SRC_URI =\"$(git remote get-url origin  | sed  's/https:/git:/g');protocol=https;branch=$(git rev-parse --abbrev-ref HEAD)\""
                SRCREV="SRCREV = \"$(git rev-parse HEAD)\""
                echo ${SRC_URI} | tee -a ${result_branch_info}
                echo ${SRCREV} | tee -a  ${result_branch_info}
                echo "" | tee -a  ${result_branch_info}
            }
            popd
        fi

    done
    echo "---------------check repo info in the yocto (end)--------------" | tee -a ${result_branch_info}
    echo "" | tee -a ${result_branch_info}

    cp ${result_branch_info} ${LOG_PATH}/yocto-build-${DATE}
    if [[ $? -ne 0 ]]; then
        echo "[ERR ] Failed to copy [${result_branch_info}] TO [${LOG_PATH}/yocto-build-${DATE}]."
    else
        echo "[INFO ] copy [${result_check_log}] TO [${LOG_PATH}/yocto-build-${DATE}] Succ."
    fi 
}

function update_bb_file
{
    if [[ -e ${1} ]]; then
        echo ">>>>>>>>>>>>>>>>>>>>>>>>>> [${1}] >>>>>>>>>>>>>>>>>>>>>>>>>>>"
        cat ${1}
    else
        echo "[ERR ] >>>>>>>>>>>>> [${1}] file is not found !!! >>>>>>>>>>>>>"
        abnormal_exit
    fi
    echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> [${1}] End >>>>>>>>>>>>>>>>>>>>>>>>"
    echo ""
    echo ">>>>>>>>>>>>>>>>>>>>>>>>>> update_bb_file start >>>>>>>>>>>>>>>>>>>>>>>>>>>"
    for repo_info in ${REPO_RECIPES[@]}; do
        local tmp_date=(${repo_info//:/ })
        local repo_name=${tmp_date[0]}
        local repo_path=${tmp_date[1]}
        local repo_bb_file=${tmp_date[2]}
        local repo_srcuri_name=${tmp_date[3]}
        local repo_srcrev_name=${tmp_date[4]}

        local repo_srcuri=$(grep ${repo_name}_SRC_URI ${1} | cut -d = -f 2)=$(grep ${repo_name}_SRC_URI ${1} | cut -d = -f 3)=$(grep ${repo_name}_SRC_URI ${1} | cut -d = -f 4)
        if [[ ! ${repo_srcuri} ]]; then
            echo "[ERR ] [${repo_name}_SRC_URI] is not found from [${1}]!!!"
            abnormal_exit
        fi 
        echo "[INFO ] >>>>>>>>>>> update [${HOME_REPO_PATH}/${repo_path}/${repo_bb_file}] start "
        echo "[INFO ] repo_srcuri=[${repo_srcuri}]"
        local repo_srcrev=$(grep ${repo_name}_${repo_srcrev_name} ${1}| cut -d = -f 2)
        echo "[INFO ] repo_srcrev=[${repo_srcrev}]"

        pushd ${HOME_REPO_PATH}/${repo_path}
        { 

            local bb_srcurl=$(grep \#${repo_srcuri_name} ${repo_bb_file})
            if [[ ! ${bb_srcurl} ]]; then
                echo "[INFO ] #${repo_srcuri_name} does not exist, first"
                sed -ri "s/^${repo_srcuri_name}/#${repo_srcuri_name}/g" ./${repo_bb_file}
                sed -ri "/^#${repo_srcuri_name}.*/a\SRC_URI =${repo_srcuri}" ./${repo_bb_file}

                sed -ri "s/^${repo_srcrev_name}/#${repo_srcrev_name}/g" ./${repo_bb_file}
                sed -ri "/^#${repo_srcrev_name}.*/a\SRCREV =${repo_srcrev}" ./${repo_bb_file}
            else
                echo "[INFO ] #${repo_srcuri_name} is exist, second"
                sed -ri "/^SRC_URI/d" ./${repo_bb_file}
                sed -ri "/^SRCREV/d" ./${repo_bb_file}
                
                sed -ri "/^#${repo_srcuri_name}.*/a\SRC_URI =${repo_srcuri}" ./${repo_bb_file}
                sed -ri "/^#${repo_srcrev_name}.*/a\SRCREV =${repo_srcrev}" ./${repo_bb_file}
            fi

            echo "[INFO ] <<<<<<<<<<< update [${HOME_REPO_PATH}/${repo_path}/${repo_bb_file}] end "
            echo ""
        }
        popd

    done

    mv ${LOG_PATH}/yocto-build-${DATE}/* ${LOG_PATH}/yocto-build-${DATE}-bak
    if [[ $? -ne 0 ]]; then
        echo "[ERR ] Failed to mv [${LOG_PATH}/yocto-build-${DATE}/*] TO [${LOG_PATH}/yocto-build-${DATE}-bak]."
    else
        echo "[INFO ] mv [${LOG_PATH}/yocto-build-${DATE}/*] TO [${LOG_PATH}/yocto-build-${DATE}-bak] Succ."
    fi 

    cp ${1} ${LOG_PATH}/yocto-build-${DATE}
    if [[ $? -ne 0 ]]; then
        echo "[ERR ] Failed to copy [${1}] TO [${LOG_PATH}/yocto-build-${DATE}]."
    else
        echo "[INFO ] copy [${1}] TO [${LOG_PATH}/yocto-build-${DATE}] Succ."
    fi 
    echo "<<<<<<<<<<<<<<<<<<<<<<<< update_bb_file end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
    echo ""
}


######################################################
# main
######################################################
while :
do
    echo "#####################################################################"
    echo "#         Please select one of the options below to proceed         #"
    echo "# Options:                                                          #"
    echo "#         1   Yocto Build Result backup and result_check            #"
    echo "#         2   update_bb_file txt                                    #"
    echo "#         0   exit                                                  #"
    echo "#####################################################################"

    read -p "Please enter your options:" options
    echo ""
    
    case ${options} in
            1)
                echo "[NORMAL] >>>>>> Yocto Build Result backup Start <<<<<<"
                start_run
                runtime_docker_backup
                result_check
                succ_exit
                echo "[NORMAL] >>>>>> Yocto Build Result backup End  <<<<<<"
                ;;
            2)
                read -p "Please enter your branch file:" ver
                echo "[NORMAL] >>>>>> update_bb_file Start <<<<<<"
                start_run
                update_bb_file ${ver}
                succ_exit
                echo "[NORMAL] >>>>>> update_bb_file End  <<<<<<"
                ;;
            0)
                echo "[NORMAL] -- exit 0 --"
                exit 0
                ;;
            *)
                echo "[ERROR ] ------ wrong option = [ ${options} ]!!! ------"
                ;;
    esac
done
